package com.ce.framework.struts2.converter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import com.ce.framework.util.StringUtil;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;

public class DateConverter extends DefaultTypeConverter {
	private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@SuppressWarnings("rawtypes")
	public Object convertValue(Map ognlContext, Object value, Class toType) {
		Object result = null;
		if (toType == Date.class) {
			result = doConvertToDate(value);
		} else if (toType == String.class) {
			result = doConvertToString(value);
		}
		return result;
	}

	private Date doConvertToDate(Object value) {
		Date result = null;

		if (value instanceof String) {
			if(StringUtil.isBlank((String)value)){
				return null;
			}
			try {
				String[] ds = ((String)value).split("\\D");
				int[] dds = new int[7];
				for(int i=0;i<dds.length;i++){
					dds[i] = 0;
					try {
						dds[i] = Integer.parseInt(ds[i]);
					} catch (Exception e) {
					}
				}
				Calendar c = Calendar.getInstance();
				c.set(dds[0],dds[1]-1,dds[2],dds[3],dds[4],dds[5]);
				result = c.getTime();
			} catch (Exception e) {
				// e.printStackTrace();
				System.out.println("dateconverter is failed!");
			}
		} else if (value instanceof Object[]) {
			// let's try to convert the first element only
			Object[] array = (Object[]) value;
			if ((array != null) && (array.length >= 1)) {
				value = array[0];
				result = doConvertToDate(value);
			}
		} else if (Date.class.isAssignableFrom(value.getClass())) {
			result = (Date) value;
		}
		return result;
	}

	private String doConvertToString(Object value) {
		String result = null;
		if (value instanceof Date) {
			result = sdf1.format(value);
		}
		return result;
	}
}
